package cn.myxl.smart.devkit.commit.persistent;

import cn.myxl.smart.devkit.commit.model.CommitTypeEnum;
import cn.myxl.smart.devkit.core.constant.SMDConstants;
import cn.myxl.smart.devkit.commit.model.CommitType;
import cn.myxl.smart.devkit.commit.model.SettingState;
import com.intellij.openapi.components.*;
import com.intellij.util.xmlb.XmlSerializerUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Service
@State(name = SMDConstants.SETTING_NAME, storages = {@Storage(value = SMDConstants.SETTING_FILE)})
@Slf4j
public final class HelperSetting implements PersistentStateComponent<HelperSetting> {

	private SettingState state;

	@Override
	public HelperSetting getState() {
		if (state == null) {
			state = loadDefaultSetting();
		}

		return this;
	}

	@Override
	public void loadState(@NotNull HelperSetting state) {
		XmlSerializerUtil.copyBean(state, this);
	}

	private SettingState loadDefaultSetting() {
		log.info("this is working!");

		SettingState defaultState = new SettingState();

		defaultState.setTemplate(SMDConstants.DEFAULT_TEMPLATE);
		List<CommitType> typeAliases = new LinkedList<>();

		Arrays.stream(CommitTypeEnum.values()).forEach(item ->  typeAliases.add(new CommitType(item.title, item.description)));

		defaultState.setTypeAliases(typeAliases);

		return defaultState;
	}

	public SettingState getSettingState() {
		return getState().state;
	}

	public void updateSettingState(SettingState settingState) {
		state = settingState;
	}
}
